package training.minggu5.maven.ui.servlet;

import java.io.IOException;
import java.math.BigDecimal;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import training.minggu5.maven.domain.Barang;
import training.minggu5.maven.service.BarangService;


public class EditBarang extends HttpServlet {

    private BarangService barvice;

    @Override
    public void init(ServletConfig config) throws ServletException {
	ApplicationContext ctx = WebApplicationContextUtils
		.getWebApplicationContext(config.getServletContext());

	barvice = (BarangService) ctx.getBean("barangService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html");

        String nama = barvice.findBarangByKode(req.getParameter("k")).getNamaBarang();
        String price = barvice.findBarangByKode(req.getParameter("k")).getUnitPrice().toString();

        String out = "<h1>edit "+req.getParameter("k")+"</h1>";
        out += "<form action='simpanBarang' method='POST'>";
        out += "<input type='hidden' name='kode' value='"+req.getParameter("k")+"'/>";
        out += "<table><tr>";
        out += "<td>kode barang</td><td>:</td>";
        out += "<td><input type='text' name='kode' value='"+req.getParameter("k")+"' disabled/></td></tr>";
        out += "<tr><td>nama barang</td><td>:</td>";
        out += "<td><input type='text' name='nama' value='"+nama+"' /></td></tr>";
        out += "<tr><td>unit price</td><td>:</td>";
        out += "<td><input type='text' name='unitprice' value='"+price+"'/></td></tr>";
        out += "<tr><td><input type='submit' value='simpan' /></td>";
        out += "<td><input type='button' value='cancel' on_click='history.back()' /></td>";

        resp.getWriter().print(out);
        resp.getWriter().close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String kode = req.getParameter("kode");
	String nama = req.getParameter("nama");
        String price = req.getParameter("unitprice");

        Barang g = new Barang();
	g.setKodeBarang(kode);
	g.setNamaBarang(nama);
        g.setUnitPrice(new BigDecimal(price));

	barvice.saveBarang(g);
	resp.sendRedirect("muka");
    }



}
